import {Injectable} from '@angular/core';
import {HttpService} from "@core/http/http.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import * as API from "@api/index";
import {AuthService} from "@shared/service/auth/auth.service";
import {Observable} from "rxjs/Observable";


import {Router} from "@angular/router";
import {
  CommonPageVo, groupInfoVO, MatchSignResp, MatchSignUpData, MatchTeamSignResp, SNSResult,
  UserAlbumFile
} from "@interface/index";
// import {SNSResult} from "@interface/interface/interface.model";
// import {groupInfoVO, MatchSignResp, MatchTeamSignResp, UserAlbumFile} from "@interface/match/match.model";
//
// import {CommonPageVo, MatchSignUpData} from "@interface/shared/shared.model";


@Injectable()
export class SignUpService {
  public contactList: Array<any> = [];

  constructor(
    public httpService: HttpService,
    public toolsService: ToolsService,
    private auth: AuthService,
    private router: Router
  ) {
  }

  toSign(data: any): Observable<SNSResult<MatchSignResp>> {  // 报名
    return this.httpService.postUrlencodeStr(API.SIGN_URL, data).map(res => res.json());
  }

  // 查询MatchId
  GetMatchId(goodid: any) {
    const url = API.GetMatchId_URL + '?goodsCode=' + goodid;
    return this.httpService.get(url).map(res => res.json());
  }

  // 查询skuDetail
  GetSkuDetail(skuCode: any) {
    const url = API.GET_SKU_DETAIL_URL + '?skuCode=' + skuCode;
    return this.httpService.get(url).map(res => res.json());
  }

  /**
   * @description 获取培训报名信息
   * @author ouyqx-691
   * @date 2017-09-18
   * @param courseId 课程id
   */
  getTrainSignFields(courseId: string) {
    const url = API.TRAINSIGNFIELDS_URL + `?courseId=${courseId}`;
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description 培训报名
   * @author ouyqx-691
   * @date 2017-09-18
   * @param courseId 课程id
   */
  trainAdd(data) {
    const url = API.ADDTRAIN_URL;
    return this.httpService.postUrlencode(url, data).map((res) => res.json());
  }

  /**
   * @description 完善票务人信息
   * @author ouyqx-691
   * @date 2017-09-18
   * @param data 票务人信息表单数据
   *
   * @modify
   * @description @完善票务信息，添加一个取票方式字段
   * @author zhoukf-1349
   * @date 2017-10-20
   */
  insertTicketerInfo(data) {
    const url = API.INSERT_TICKET_HOLDER_INFO_URL;
    return this.httpService.postUrlencode(url, data).map(res => res.json());
  }


  /**
   * @description 获取赛事详情信息
   * @param matchId
   * @param orderNumber
   */
  getDynamicMatchInfo(matchId: string, orderNumber: string) {
    const userId = this.auth.getUserId();
    const url = API.MACTH_SIGN_FIELD_URL + `?matchId=${matchId}&userId=${userId}&orderNumber=${orderNumber}`;
    return this.httpService.get(url).map(res => res.json());
  }

  /**
   * @description 团体报名暂存信息
   * @param matchId
   * @param orderNumber
   */
  addMatchTeamSign(data: any): Observable<SNSResult<CommonPageVo<groupInfoVO>>> {
    const url = API.GROUP_SIGN_URL;
    return this.httpService.postUrlencodeStr(url, data).map(res => res.json());
  }

  /**
   * @description 获取票务方式
   * @author @zhoukf1349
   * @date 20171018
   * @type {string}
   */

  getObtainType(goodsCode: string) {
    const url = API.TICKET_GET_OBTAIN_TYPE + `?goodsCode=${goodsCode}`;
    return this.httpService.get(url).map(res => res.json());
  }


  // 查詢訂單信息
  getOrderInfo(orderNumber: string) {
    return this.httpService.get(API.ORDER_INFO_URL + `?orderNumber=${orderNumber}`).map(res => res.json());
  }

  // 团体报名 选择群并报名
  groupChooseGroup(data: any): Observable<SNSResult<MatchTeamSignResp>> {
    const url = API.GROUP_SIGN_CHOOSEGROUP_URL;
    return this.httpService.postUrlencode(url, data).map(res => res.json());
  }

  /**
   * @description   // 获取俱乐部列表
   * @author ouxh
   * @date 2017-08-13
   * @param page:number
   */
  getUserClubList(page: number): Observable<SNSResult<CommonPageVo<groupInfoVO>>> {
    const url = API.USER_GROUP_LIST + `?pageNum=${page}&pageSize=10`;
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description // 团体报名 创建俱乐部并报名
   * @author ouxh
   * @date 2017-08-13
   * @param data 类型 data = {
        groupName: '',
        groupLogo: '',
        orderNumber: ''
      }
   */
  groupCreateGroup(data: any): Observable<SNSResult<MatchTeamSignResp>> {  // 团体报名 创建俱乐部并报名
    const url = API.GROUP_SIGN_CREATEGROUP_URL;
    return this.httpService.postUrlencode(url, data).map(res => res.json());
  }

  /**
   * @description / 上传文件
   * @author ouxh
   * @date 2017-08-13
   * @param file 选中的文件
   * @param purpose 上传的类型 资源文件用途：1,用户相册图；2,IP推荐图；3,用户上传视频;4,直播直播封面;5,举报图片;6,直播回放封面;7,组织logo
   * @param type 上传的类型 资源文件类型:2图片3视频
   */
  // 上传文件
  upLoadFile(file, purpose: string, type: string): Observable<SNSResult<UserAlbumFile>> {
    const url = API.UPLOADFILE_URL;
    const formData = new FormData();
    formData.append('purpose', purpose);
    formData.append('type', type);
    return this.httpService.uploadFile(url, file, formData).map((res) => res.json());
  }

  /**
   * @description 获取赛事验证码短信
   * @author ouxh
   * @date 2017-08-13
   * @param type 类型 1 是赛事 则data里要包含 matchId \ channelsId
   */
  getSmsCode(type: string, data: any) {
    let url = '';
    const phone = data['checkNum'];
    if (type === '1') { // 赛事
      const matchId = data['matchId'];
      if (data['channelsId']) {
        const channelsId = data['channelsId'];
        url = API.MATCH_SMS_CODE + `?phone=${phone}&matchId=${matchId}&channelId=${channelsId}`;
      } else {
        url = API.MATCH_SMS_CODE + `?phone=${phone}&matchId=${matchId}`;
      }
    } else {
      url = API.MATCH_SMS_CODE + `?phone=${phone}`;
    }
    return this.httpService.get(url).map((res) => res.json());
    ;
  }

  /**
   * @description 获取赛事验证码短信
   * @author ouxh
   * @date 2017-08-13
   * @param code 验证码
   * @param phone 手机号
   */
  validSmsCode(code: string, phone: string) {
    const url = API.MATCH_VALID_SMS + `?validateMsg=${code}&operateType=6&validateType=5&somethingStr=${phone}`;
    return this.httpService.get(url).map((res) => res.json());
  }

  /**
   * @description  请求报名接口返回的年龄限制信息
   * @author ouxh
   * @date 2017-10-26
   * @param data : {data:[],minAge:string,maxAge:string} data里面包含data（返回的错误信息的类型不固定，所以给了data字段）
   */
  getAgeLimitMsg(data: any) {
    let str = '';
    if (data.data && data.data.length > 0) {
      data.data.forEach((e, i) => {
        if (i === data.data.length - 1) {
          str += `${e} `;
        } else {
          str += `${e}、 `;
        }
      });
    }
    return {
      minAge: data.minAge,
      maxAge: data.maxAge,
      title: `参赛人年龄不符 ${data.minAge} ~ ${data.maxAge} 岁`,
      memberStr: str
    };
  }

  /**
   * @description  请求报名接口返回的已报名的成员字符串
   * @author ouxh
   * @date 2017-10-26
   * @param data : [{idNo:string,phone::string}]
   * @return array
   */
  getHasSignMemberStr(data: any) {
    const str = [];
    data.forEach((e, i) => {
     /* str.push(`手机号:${e.phone}`);
      str.push(`证件号:${e.idNo}`);*/
     str.push(`手机号:${e.phone}`, `证件号:${e.idNo}`);
    });
    return str;
  }

  /**
   * @description 组装赛事表单请求数据
   * @author ouxh
   * @date 2017-10-26
   * @param MatchSignUpData 组装赛事表单请求数据
   */
  getPerasonalSignData(params: MatchSignUpData): MatchSignUpData {

    const data = new MatchSignUpData();
    data['deviceType'] = '4';
    data['matchId'] = params.matchId;
    data['orderNumber'] = params.orderNumber;

    if (params.channelsId) {
      data['channelsId'] = params.channelsId;
    }
    if (params.groupType) {
      data['groupType'] = params.groupType;
    }
    return data;
  }

  /**
   * @description 判断双打赛事的参赛类型
   * @author ouxh
   * @date 2017-10-26
   * @param type 单双打字段： 男子单打:1, 女子单打：2, 男子双打：11, 女子双打：22 ,混双：12
   */
  getDoubleMatchSignType(type: string) {
    switch (type) {
      case '1':
        return '男单';
      case '2':
        return '女单';
      case '11':
        return '男双';
      case '22':
        return '女双';
      case '12':
        return '混双';
      default:
        return '';
    }
  }

  /**
   * 判断订单的状态，待支付或者已支付，转跳支付页或者支付完成页面
   * status : 1: 待支付, 2: 已支付, 3: 支付失败, 4: 已完成, 5: 已关闭, 6: 退款中, 7: 已退货, 9: 预下单, 10: 已取消
   * @param {number} status
   * @param {string} orderNumber
   */
  goToPayOrResult(status: number, orderNumber: string) {
    if (status === 1) {
      this.router.navigate(['/payment/pay'], {
        queryParams: { orderNumber: orderNumber } });
    }else if (status === 2) {
      this.router.navigate(['/payment/result'], {
        queryParams: {mchOrderNumber: orderNumber}});
    }
  }

}
